<template>
    <JzlPageBuilderWeb
      v-if="inited && iPageType == 1"
      :in-page-id="iPageId"
      :app-id="iAppId"
      :type="iPageType"
      v-bind="$attrs"
      @changePage="handleChangePage"
    />
    <JzlPageBuilderPc
      v-else-if="inited && iPageType == 5"
      :in-page-id="iPageId"
      :app-id="iAppId"
      :type="iPageType"
      v-bind="$attrs"
      @changePage="handleChangePage"
    />
    <JzlPageBuilderH5
      v-else-if="inited"
      :in-page-id="iPageId"
      :app-id="iAppId"
      v-bind="$attrs"
      @changePage="handleChangePage"
    />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import _ from 'lodash';
import JzlPageBuilderH5 from './builder-h5.vue';
import JzlPageBuilderWeb from './builder-web.vue';
import JzlPageBuilderPc from './builder-pc.vue';
import {api} from "@jzl/api";

const props = defineProps({
  inPageId: { type: [Number] },
  appId: { type: [Number] },
  pageType: { type: [Number] }
});

const emit = defineEmits(['changePage']);

const inited = ref(false);
const iPageId = ref(null);
const iAppId = ref(null);
const iPageType = ref(2);

const init = async () => {
  inited.value = false;
  let pageId = window.location.search.getQuery('id');
  let appId = window.location.search.getQuery('appId');
  let pageType = window.location.search.getQuery('pageType');

  let currentIPageId = props.inPageId || pageId;
  let currentIPageType = props.pageType || pageType;
  let currentIAppId = props.appId || appId;

  if (currentIPageId && !currentIPageType) {
    let page = await api.page.getPage(currentIPageId);
    let type = _.get(page, 'type');
    if (type) currentIPageType = type;
  }

  iPageId.value = currentIPageId;
  iPageType.value = currentIPageType || 2;
  iAppId.value = currentIAppId;
  inited.value = true;
};

const handleChangePage = (info) => {
  let pageId = _.get(info, "page_id");
  let type = _.get(info, "type");

  if (pageId) {
    // 这里假设 $confirm 是挂载在全局的
    $jui.confirm('切换页面, 此前修改内容将会丢失，确定切换?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      iPageId.value = pageId;
      iPageType.value = type;
    }).catch(() => {});
  }
};

onMounted(() => {
  init();
});

watch(() => props.inPageId, () => {
  init();
});
</script>
